﻿using KongMing.ORM.SqlSugar.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KongMing.ORM.SqlSugar
{
    public class 多线程操作
    {
        public static void Go()
        {
            AddProjects().Wait();
        }


        public async static Task AddProjects()
        {
            var projects = new ConcurrentBag<Project>();
            Random random = new Random();
            var cts = new CancellationTokenSource();
            using (var db = SqlSugarHelper.GetDB())
            {
                try
                {
                    db.BeginTran();
                    Parallel.For(1, 11, new ParallelOptions { CancellationToken = cts.Token, MaxDegreeOfParallelism = 10 }, i =>
                    {
                        try
                        {
                            var project = new Project
                            {
                                ProjectId = i,
                                ProjectName = $"项目 {i} ",
                                ProjectType = random.Next(0, 3),
                                Status = 0,
                                Sort = i
                            };
                            projects.Add(project);
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    });
                    int res = await db.Insertable(projects.ToList()).ExecuteCommandAsync();
                    db.CommitTran();
                }
                catch (AggregateException aex)
                {
                    cts.Cancel();
                    StringBuilder stringBuilder = new StringBuilder("异常信息：");
                    foreach (var item in aex.InnerExceptions)
                    {
                        stringBuilder.AppendLine(item.Message);
                    }
                    throw new Exception(stringBuilder.ToString());
                }
                catch (Exception ex)
                {
                    db.RollbackTran();
                    throw ex;
                }
            }
        }
    }
}
